#!/bin/bash
set -eo pipefail

SUCCESS_TXT="${GREEN}[SUCCESS]${NC}"

src_file=$1
exe_file=$(basename "${src_file%.*}")

if [[ -z "$MACHINE" ]]; then
  echo "Must provide MACHINE for compile"
  exit 1
fi

if [[ "$MACHINE" == "Windows" ]]; then
  exe_file=$(basename "${src_file%.*}".exe)
fi

if [[ -z "$src_file" ]]; then
  echo "Must provide \$1 for compile"
  exit 1
fi

if [[ -z "$CPP_INCLUDE_DIR" ]]; then
  echo "Must provide CPP_INCLUDE_DIR in environment"
  exit 1
fi

if [[ -z "$CPP" ]]; then
  echo "Must provide CPP in environment"
  exit 1
fi

rm -f "$exe_file"

EXTRA_ARGS=""

if [[ -z "${TESTLIB_COMPILER_OPTIMIZATION_OPT}" ]]; then
    OPTIMIZATION="2"
else
    OPTIMIZATION="${TESTLIB_COMPILER_OPTIMIZATION_OPT}"
fi

if [[ "$CPP" == "cl.exe" ]]; then
  echo "Compiling $src_file, running:" "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O${OPTIMIZATION}" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file"
  "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O${OPTIMIZATION}" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file"
else
  "$CPP" --version
  dir=$(dirname "$CPP")
  if [[ "$dir" == *"/bin" ]] || [[ "$MACHINE" == "Windows" ]]; then
    EXTRA_ARGS="${EXTRA_ARGS} -static"
  fi
  echo "Compiling $src_file, running:" "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" "-O${OPTIMIZATION}" "$src_file"
  eval "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" "-O${OPTIMIZATION}" "$src_file"
fi

rm -f ./*.o ./*.obj

if [ ! -f "$exe_file" ]; then
  echo "Compilation failed: file $exe_file not found"
  exit 1
fi

echo -e "${SUCCESS_TXT} $src_file compiled\n"

if [[ "$2" == "--check-only" ]]; then
  rm -rf "$exe_file"
fi
